//
//  TouchViewCell.m
//  A段项目
//
//  Created by dllo on 16/2/24.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "TouchViewCell.h"
#import <UIImageView+WebCache.h>
#import "UMSocialDataService.h"
#import "UMSocial.h"
#import "Model.h"
#import <MBProgressHUD.h>
#import "UMSocial.h"
#import "TouchFirstView.h"
#import "FMDBDataHandler.h"
#import "Person.h"






@interface TouchViewCell () <UIGestureRecognizerDelegate>


@property (nonatomic, retain) UIButton *buttonForDownLoad;
@property (nonatomic, retain) UIButton *buttonForShare;
@property (nonatomic, retain) UIView *viewForThis;
@property (nonatomic, retain) UIButton *colleect;
@property (nonatomic, retain) NSString *pic;




@end

@implementation TouchViewCell

{
    
    BOOL exist; //表示是否 收藏过.
}

- (void)dealloc {
    
    [super dealloc];
    
    [_buttonForShare release];
    
    [_buttonForDownLoad release];
    
    [_viewForThis release];
    
    [_colleect release];
    
    [_pic release];
    
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.imageViewForTouch = [[UIImageView alloc] init];
        
        self.viewForThis = [[UIView alloc] init];
        
        self.colleect = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.contentView addSubview:self.colleect];
        
        [self addSubview:self.viewForThis];
        [self.contentView addSubview:self.imageViewForTouch];
        
        /**添加手势. */
          UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];
        
        pinch.delegate = self;
        
        [self.imageViewForTouch addGestureRecognizer:pinch];
        
        self.imageViewForTouch.userInteractionEnabled = YES;
        
        [self.imageViewForTouch becomeFirstResponder];
        
        [pinch release];
        
        
        
        /**添加拖拽手势. */
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragAction:)];
        
        pan.delegate = self;
        
        [self.imageViewForTouch addGestureRecognizer:pan];
        
        [pan release];
        
        
        
        self.buttonForDownLoad = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [self.contentView addSubview:self.buttonForDownLoad];
        
        self.buttonForShare = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.contentView addSubview:self.buttonForShare];
        
        [self.imageViewForTouch release];
        
        [self.viewForThis release];
        
    
        
    }
    return self;
}

/**对视图进行布局. */
- (void)layoutSubviews {
    
    [super layoutSubviews];
    
   // self.layer.borderWidth = 10;
   // self.layer.masksToBounds = YES;
    self.layer.borderColor = [[UIColor whiteColor]CGColor];
    
    self.imageViewForTouch.layer.borderWidth = 10;
    self.imageViewForTouch.layer.borderColor = [[UIColor whiteColor]CGColor];
    
    self.imageViewForTouch.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - 200);
    
  
    
    
  /**设置圆角.*/
    self.imageViewForTouch.layer.cornerRadius = 10;
    self.imageViewForTouch.layer.masksToBounds = YES;
    self.imageViewForTouch.center = self.contentView.center;
    
  
    self.buttonForDownLoad.frame = CGRectMake(20, self.bounds.size.height - 100, 50, 50);
    
    [self.buttonForDownLoad setImage:[UIImage imageNamed:@"downLoad"] forState:UIControlStateNormal];
    
    [self.buttonForDownLoad addTarget:self action:@selector(downAction:) forControlEvents:UIControlEventTouchUpInside];
    
    /**收藏按钮的位置.*/
    self.buttonForShare.frame = CGRectMake(self.bounds.size.width - 70, self.bounds.size.height - 100, 50, 50);
    
    self.colleect.frame = CGRectMake((self.bounds.size.width - 70 + 20)/2, self.bounds.size.height - 100, 50, 50);
    
    [self.colleect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
      self.buttonForDownLoad.tintColor = [UIColor whiteColor];
    
    [self.buttonForShare setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    
    [self.buttonForShare addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

/*点击下载. */

- (void)downAction:(UIButton *)button {
    
    id object = [self nextResponder];
    
    while (![object isKindOfClass:[TouchFirstView class]]&&object != nil) {
        
        object = [object nextResponder];
        
    }
    TouchFirstView *touchuView = (TouchFirstView *)object; //找对象.
    
    
    /**MBProgress 控件. */
    [MBProgressHUD showHUDAddedTo:touchuView.view animated:YES];
    
    __block typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        UIImageWriteToSavedPhotosAlbum(weakSelf.imageViewForTouch.image,weakSelf, @selector(image: didFinishSavingWithError: contextInfo:), nil);
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:touchuView.view animated:YES];
            
        });
    });

}


/*图片保存成功. */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    id object = [self nextResponder];
    
    while (![object isKindOfClass:[TouchFirstView class]]&&object != nil) {
        
        object = [object nextResponder];
        
    }
    TouchFirstView *touchuView = (TouchFirstView *)object;

    
    if(!error){
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存成功" preferredStyle:1];
        
        [touchuView presentViewController:alert animated:YES completion:^{
            
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存失败" preferredStyle:1];
        
        [touchuView presentViewController:alert animated:YES completion:^{
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        
    }
}

#pragma mark -- 手势.

- (void)pinchAction:(UIPinchGestureRecognizer *)pinch {
    

    
    pinch.view.transform = CGAffineTransformScale(pinch.view.transform, pinch.scale,pinch.scale);
    
    pinch.scale = 1;
    
    if (pinch.state == 3) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.imageViewForTouch.transform = CGAffineTransformIdentity;
            
        }];
        
    }

    
}

- (void)dragAction:(UIPanGestureRecognizer *)pan {
    
    CGPoint point = [pan translationInView:pan.view];

    /** 更改 self.ImageView.transform属性. */
    pan.view.transform = CGAffineTransformTranslate(pan.view.transform, point.x, point.y);
    
    
    NSLog(@"----%ld",pan.state);
    /** 参考点归零. */
    [pan setTranslation:CGPointZero inView:pan.view];
    
    
    if (pan.state == 3) {
        
        __block typeof(self)weakSelf = self;
        [UIView animateWithDuration:0.5 animations:^{
            
            weakSelf.imageViewForTouch.transform = CGAffineTransformIdentity;
            
        }];
        
    }
    
    
    
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
    return YES;
    
}



/**收藏. */

- (void)collectAction:(UIButton *)button {
  
    id object = [self nextResponder];
    
    while (![object isKindOfClass:[TouchFirstView class]]&&object != nil) {
        
        object = [object nextResponder];
        
    }
    
    /**是否收藏过. */
    if (!exist) {
        
    //    Student *image = [[Student alloc] init];
        
        Person *per = [[Person alloc] init];
        
        per.data = UIImageJPEGRepresentation(self.imageViewForTouch.image, 1);
        
        per.number = 200;
        
        per.name = [NSString stringWithString:self.pic];
        
        [self.colleect setImage:[UIImage imageNamed:@"xingxing2"] forState:UIControlStateNormal];
        
        
        //如果没收藏过 直接插入
        [[FMDBDataHandler shareDataBaseHandler]insertInfo:per];
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"收藏成功" preferredStyle:1];
        
        [object presentViewController:alert animated:YES completion:^{
            
            [alert dismissViewControllerAnimated:YES completion:nil];

        }];
        
        exist = YES;
        
    }else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你已经收藏过了!" preferredStyle:1];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:1 handler:nil];
        
        [alert addAction:action];
        
        [object presentViewController:alert animated:YES completion:nil];
    
        
    }

}



/*点击分享. */
- (void)shareAction:(UIButton *)button {
    
    
    id object = [self nextResponder];
    
    while (![object isKindOfClass:[TouchFirstView class]]&&object != nil) {
        
        object = [object nextResponder];
        
    }
    
    TouchFirstView *touchView = (TouchFirstView *)object;
    
    
    [UMSocialSnsService presentSnsIconSheetView:touchView
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"这是我刚浏览的图片,觉得不错,你也看看吧!"
                                     shareImage:self.imageViewForTouch.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToDouban,UMShareToWechatTimeline,nil]
                                       delegate:nil];
    
    
}

- (void)passedInfoImage:(Model *)modle {
    
    [self.imageViewForTouch sd_setImageWithURL:[NSURL URLWithString:modle.url]];

    
        self.pic = [NSString stringWithString:modle.url];
        
    
    /*查询数据库.判断是否收藏过此图片. */
    
    NSArray *array = [[FMDBDataHandler shareDataBaseHandler]selectedForNanme:modle.url];
    
  
    
    if (array.count == 0) {
        
        [self.colleect setImage:[UIImage imageNamed:@"xingxing"] forState:UIControlStateNormal]; //没有收藏过
        
        exist = NO;
        
        
    }else {
        
        
        [self.colleect setImage:[UIImage imageNamed:@"xingxing2"] forState:UIControlStateNormal]; //有收藏过
        
        exist = YES;
        
    }
    
}




@end
